<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 会员卡申请追加
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m310030_000011_t_vipcard_card_order_trade extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%card_order}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%card_order}}')->andWhere(['!=', 'expired_at', 0]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            if ($row['status'] < 0) {
                continue;
            }
            $trade = (new Query())->from('{{%trade}}')->andWhere(['unified_no' => $row['expired_at']])->one();

            $connect->update($migration->tableName, [
                'trade_id' => $trade['id'],
                'out_trade_no' => $trade['trade_no'],
                'pay_time' => $trade['updated_at'],
                'expired_at' => 0,
                'status' => 20,
            ], [
                'id' => $row['id']
            ])->execute();
        }
    }

}
